package com.koushikdutta.ion;

import android.content.Context;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.ImageView;
import com.google.gson.Gson;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpClientMiddleware;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.http.ResponseCacheMiddleware;
import com.koushikdutta.async.http.libcore.RawHeaders;
import com.koushikdutta.async.util.FileCache;
import com.koushikdutta.async.util.FileUtility;
import com.koushikdutta.async.util.HashList;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import com.koushikdutta.ion.bitmap.IonBitmapCache;
import com.koushikdutta.ion.builder.Builders.Any.B;
import com.koushikdutta.ion.builder.Builders.IV.F;
import com.koushikdutta.ion.builder.LoadBuilder;
import com.koushikdutta.ion.conscrypt.ConscryptMiddleware;
import com.koushikdutta.ion.cookie.CookieMiddleware;
import com.koushikdutta.ion.loader.AssetLoader;
import com.koushikdutta.ion.loader.AsyncHttpRequestFactory;
import com.koushikdutta.ion.loader.ContentLoader;
import com.koushikdutta.ion.loader.FileLoader;
import com.koushikdutta.ion.loader.HttpLoader;
import com.koushikdutta.ion.loader.PackageIconLoader;
import com.koushikdutta.ion.loader.ResourceLoader;
import com.koushikdutta.ion.loader.VideoLoader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;

public class Ion {
    static int availableProcessors = Runtime.getRuntime().availableProcessors();
    static ExecutorService bitmapExecutorService = (availableProcessors > 2 ? Executors.newFixedThreadPool(availableProcessors - 1) : Executors.newFixedThreadPool(1));
    static HashMap<String, Ion> instances = new HashMap();
    static ExecutorService ioExecutorService = Executors.newFixedThreadPool(4);
    static final Handler mainHandler = new Handler(Looper.getMainLooper());
    AssetLoader assetLoader;
    IonImageViewRequestBuilder bitmapBuilder = new IonImageViewRequestBuilder(this);
    IonBitmapCache bitmapCache;
    HashList<FutureCallback<BitmapInfo>> bitmapsPending = new HashList();
    Config config = new Config();
    ConscryptMiddleware conscryptMiddleware;
    ContentLoader contentLoader;
    Context context;
    CookieMiddleware cookieMiddleware;
    FileLoader fileLoader;
    Gson gson;
    AsyncHttpClient httpClient;
    HttpLoader httpLoader;
    WeakHashMap<Object, FutureSet> inFlight = new WeakHashMap();
    ArrayList<Loader> loaders = new ArrayList();
    int logLevel;
    String logtag;
    String name;
    PackageIconLoader packageIconLoader;
    private Runnable processDeferred = new Runnable() {
        public void run() {
            if (!BitmapFetcher.shouldDeferImageView(Ion.this)) {
                Iterator i$;
                DeferredLoadBitmap deferredLoadBitmap;
                ArrayList<DeferredLoadBitmap> deferred = null;
                for (String key : Ion.this.bitmapsPending.keySet()) {
                    DeferredLoadBitmap owner = Ion.this.bitmapsPending.tag(key);
                    if (owner instanceof DeferredLoadBitmap) {
                        deferredLoadBitmap = owner;
                        if (deferred == null) {
                            deferred = new ArrayList();
                        }
                        deferred.add(deferredLoadBitmap);
                    }
                }
                if (deferred != null) {
                    int count = 0;
                    i$ = deferred.iterator();
                    while (i$.hasNext()) {
                        deferredLoadBitmap = (DeferredLoadBitmap) i$.next();
                        Ion.this.bitmapsPending.tag(deferredLoadBitmap.key, null);
                        Ion.this.bitmapsPending.tag(deferredLoadBitmap.fetcher.bitmapKey, null);
                        deferredLoadBitmap.fetcher.execute();
                        count++;
                        if (count > 5) {
                            return;
                        }
                    }
                }
            }
        }
    };
    ResourceLoader resourceLoader;
    ResponseCacheMiddleware responseCache;
    FileCache storeCache;
    String userAgent;
    VideoLoader videoLoader;

    public class Config {
        AsyncHttpRequestFactory asyncHttpRequestFactory = new AsyncHttpRequestFactory() {
            public AsyncHttpRequest createAsyncHttpRequest(Uri uri, String method, RawHeaders headers) {
                AsyncHttpRequest request = new AsyncHttpRequest(uri, method, headers);
                if (!TextUtils.isEmpty(Ion.this.userAgent)) {
                    request.getHeaders().setUserAgent(Ion.this.userAgent);
                }
                return request;
            }
        };

        public synchronized Gson getGson() {
            if (Ion.this.gson == null) {
                Ion.this.gson = new Gson();
            }
            return Ion.this.gson;
        }

        public AsyncHttpRequestFactory getAsyncHttpRequestFactory() {
            return this.asyncHttpRequestFactory;
        }

        public Config addLoader(Loader loader) {
            Ion.this.loaders.add(loader);
            return this;
        }

        public List<Loader> getLoaders() {
            return Ion.this.loaders;
        }
    }

    static class FutureSet extends WeakHashMap<Future, Boolean> {
        FutureSet() {
        }
    }

    public static LoadBuilder<B> with(Context context) {
        return getDefault(context).build(context);
    }

    public static Ion getDefault(Context context) {
        return getInstance(context, "ion");
    }

    public static Ion getInstance(Context context, String name) {
        if (context == null) {
            throw new NullPointerException("Can not pass null context in to retrieve ion instance");
        }
        Ion instance = (Ion) instances.get(name);
        if (instance != null) {
            return instance;
        }
        HashMap hashMap = instances;
        instance = new Ion(context, name);
        hashMap.put(name, instance);
        return instance;
    }

    public static F<? extends F<?>> with(ImageView imageView) {
        return getDefault(imageView.getContext()).build(imageView);
    }

    private Ion(Context context, String name) {
        context = context.getApplicationContext();
        this.context = context;
        this.name = name;
        this.httpClient = new AsyncHttpClient(new AsyncServer("ion-" + name));
        this.httpClient.getSSLSocketMiddleware().setHostnameVerifier(new BrowserCompatHostnameVerifier());
        AsyncHttpClient asyncHttpClient = this.httpClient;
        AsyncHttpClientMiddleware conscryptMiddleware = new ConscryptMiddleware(context, this.httpClient.getSSLSocketMiddleware());
        this.conscryptMiddleware = conscryptMiddleware;
        asyncHttpClient.insertMiddleware(conscryptMiddleware);
        File ionCacheDir = new File(context.getCacheDir(), name);
        try {
            this.responseCache = ResponseCacheMiddleware.addCache(this.httpClient, ionCacheDir, 10485760);
        } catch (IOException e) {
            IonLog.w("unable to set up response cache, clearing", e);
            FileUtility.deleteDirectory(ionCacheDir);
            try {
                this.responseCache = ResponseCacheMiddleware.addCache(this.httpClient, ionCacheDir, 10485760);
            } catch (IOException e2) {
                IonLog.w("unable to set up response cache, failing", e);
            }
        }
        this.storeCache = new FileCache(new File(context.getFilesDir(), name), Long.MAX_VALUE, false);
        if (VERSION.SDK_INT >= 9) {
            addCookieMiddleware();
        }
        this.httpClient.getSocketMiddleware().setConnectAllAddresses(true);
        this.httpClient.getSSLSocketMiddleware().setConnectAllAddresses(true);
        this.bitmapCache = new IonBitmapCache(this);
        Config configure = configure();
        Loader videoLoader = new VideoLoader();
        this.videoLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new PackageIconLoader();
        this.packageIconLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new HttpLoader();
        this.httpLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new ContentLoader();
        this.contentLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new ResourceLoader();
        this.resourceLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new AssetLoader();
        this.assetLoader = videoLoader;
        configure = configure.addLoader(videoLoader);
        videoLoader = new FileLoader();
        this.fileLoader = videoLoader;
        configure.addLoader(videoLoader);
    }

    public static ExecutorService getBitmapLoadExecutorService() {
        return bitmapExecutorService;
    }

    public LoadBuilder<B> build(Context context) {
        return new IonRequestBuilder(ContextReference.fromContext(context), this);
    }

    public F<? extends F<?>> build(ImageView imageView) {
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            throw new IllegalStateException("must be called from UI thread");
        }
        this.bitmapBuilder.reset();
        this.bitmapBuilder.ion = this;
        return this.bitmapBuilder.withImageView(imageView);
    }

    void processDeferred() {
        mainHandler.removeCallbacks(this.processDeferred);
        mainHandler.post(this.processDeferred);
    }

    void addFutureInFlight(Future future, Object group) {
        if (group != null && future != null && !future.isDone() && !future.isCancelled()) {
            FutureSet members;
            synchronized (this) {
                members = (FutureSet) this.inFlight.get(group);
                if (members == null) {
                    members = new FutureSet();
                    this.inFlight.put(group, members);
                }
            }
            members.put(future, Boolean.valueOf(true));
        }
    }

    public Context getContext() {
        return this.context;
    }

    private void addCookieMiddleware() {
        AsyncHttpClient asyncHttpClient = this.httpClient;
        AsyncHttpClientMiddleware cookieMiddleware = new CookieMiddleware(this.context, this.name);
        this.cookieMiddleware = cookieMiddleware;
        asyncHttpClient.insertMiddleware(cookieMiddleware);
    }

    public AsyncHttpClient getHttpClient() {
        return this.httpClient;
    }

    public AsyncServer getServer() {
        return this.httpClient.getServer();
    }

    public Config configure() {
        return this.config;
    }

    public IonBitmapCache getBitmapCache() {
        return this.bitmapCache;
    }
}
